package one.stand.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.net.InetSocketAddress;

/**
 * @author Administrator
 */
@Component
public class NettyServer implements CommandLineRunner {
    @Autowired
    @Qualifier("bossGroup")
    private EventLoopGroup bossGroup;
    private Logger log = LoggerFactory.getLogger(NettyServer.class);
    @Autowired
    @Qualifier("serverBootstrap")
    private ServerBootstrap serverBootstrap;
    private ChannelFuture serverChannelFuture;
    @Autowired
    @Qualifier("tcpSocketAddress")
    private InetSocketAddress tcpPort;
    @Autowired
    @Qualifier("workerGroup")
    private EventLoopGroup workerGroup;
    @Value("${netty.n_pord}")
    private Integer nPord;
    @Value("${netty.begin_port}")
    private Integer beginPort;

    @Override
    public void run(String... args) {
        try {
            log.info("TCP Starting ....." + tcpPort);
            serverChannelFuture = serverBootstrap.bind(tcpPort).sync();
            serverChannelFuture.channel().closeFuture().sync();
            if (serverChannelFuture.isSuccess()) {
                log.info("TCP Start Success.............");
            }
        } catch (Exception e) {
            log.error("tpc start err", e);
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @PreDestroy
    public void stop() {
        log.info("TCP closeing Success.............");
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
